package com.xmutca.cloud.auth.security;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;

public class SecurityAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	private UserDetailsService userdetailsService;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		/**
		 * 系统登陆的真正核心流程
		 */
		String username = authentication.getName();//帐户
		String password = String.valueOf(authentication.getCredentials());//密码
		SecurityPrincipal principal = (SecurityPrincipal) userdetailsService.loadUserByUsername(username);

		//密码匹配验证
        if (passwordEncoder().isPasswordValid(principal.getPassword(), password, principal.getSalt())) {
            Collection<? extends GrantedAuthority> authorities = principal.getAuthorities();
            return new UsernamePasswordAuthenticationToken(principal, password, authorities);
        }
        throw new BadCredentialsException("Wrong password.");
	}

	@Override
	public boolean supports(Class<?> authentication) {
		//正常此处是要判断传参的对象，与自定义的AbstractAuthenticationToken是否符合
		return true;
	}
	
	@Bean
	public ShaPasswordEncoder passwordEncoder() {
        return new ShaPasswordEncoder(256);
    }
}
